<!DOCTYPE html>
<html>
<head>
    #include("../../_common/head.html")
    <title>系统用户</title>
    <style>
        .deptTree {
            width: 100% !important;
            height: -webkit-calc(100vh - 100px);
            height: -moz-calc(100vh - 100px);
            height: calc(100vh - 100px);
        }
    </style>
</head>
<body class="pear-container">
<div class="layui-row layui-col-space10">
    <div class="layui-col-xs12 layui-col-sm8 layui-col-md10">
        <div class="layui-panel query-panel /*查询面板*/">
            <form id="main-form" class="layui-form layui-row layui-col-space16" lay-filter="main-form" onsubmit="return false;">
                <input type="hidden" name="deptId" value="">
                <div class="layui-col-xl2 layui-col-lg2 layui-col-md2 layui-col-sm3 layui-col-xs6">
                    <div class="layui-input-wrap">
                        <div class="layui-input-prefix">
                            <i class="pear-icon pear-icon-text"></i>
                        </div>
                        <input type="text" name="word" value="#(word??)" placeholder="模糊查询" autocomplete="off" class="layui-input" lay-affix="clear">
                    </div>
                </div>
                <div class="layui-col-xl2 layui-col-lg2 layui-col-md2 layui-col-sm3 layui-col-xs6">
                    <div class="layui-input-wrap">
                        <select name="status">
                            <option value="">-- 状态 --</option>
                            #DICTS('bean_status')
                            #for(item : dicts)
                            <option value="#(item.value)"#if(status?? == item.value) selected#end>#(item.label)</option>
                            #end
                        </select>
                    </div>
                </div>
                <div class="layui-col-xl2 layui-col-lg2 layui-col-md2 layui-col-sm3 layui-col-xs6">
                    <div class="layui-btn-group">
                        <button id="main-form-search" type="button" class="layui-btn layui-btn-sm">
                            <i class="layui-icon layui-icon-search"></i> 搜索
                        </button>
                        <button id="main-form-reset" type="button" class="layui-btn layui-btn-sm layui-btn-primary">
                            <i class="layui-icon layui-icon-refresh"></i> 重置
                        </button>
                    </div>
                </div>
            </form>
        </div>
        <div class="layui-panel table-panel /*表格面板*/">
            <table id="main-table"></table>
            <script id="main-pagebar" type="text/html"></script>
        </div>
    </div>
    <div class="layui-col-xs12 layui-col-sm4 layui-col-md2 dept-tree-div">
        <div class="layui-card">
            <div class="layui-card-body">
                <div id="deptTreeContent" style="overflow: auto">
                    <ul id="deptTree" class="deptTree" data-id="deptId"></ul>
                </div>
            </div>
        </div>
    </div>
</div>

#include("../../_common/data_table_template.html")
#include("../../_common/foot.html")

<script type="text/javascript">
layui.use(['jquery', 'dropdown', 'tree'], () => {
    var $ = layui.jquery, dropdown = layui.dropdown, tree = layui.tree;
    //定义表格模块基本参数
    let module = {
        type: TABLE_TYPE.dataTable,             //表格类型：二维表格
        idField: 'id',                          //表格中 id 的字段名（与数据库定义的要一致，如userId）
        name: '系统参数',                        //表格模块的业务名称
        path: '#CTX()/admin/system/user/',      //表格模块的操作路径，以 '/' 结尾
    };

    //定义查询表单基本参数
    let queryForm = {
        id: 'main-form',                        //查询面板中 form 表单的 id 属性
        searchButtonId: 'main-form-search',     //查询面板中搜索按钮的 id 属性
        resetButtonId: 'main-form-reset',       //查询面板中重置按钮的 id 属性
    };

    //定义编辑对话框基本参数
    let editDialog = {
        submitFormId: 'edit-form',              //编辑页面（模态）中 form 表单的 ID 属性
        submitButtonId: 'submit-button',        //编辑页面（模态）中提交按钮的 ID 属性
        width: '720px',                         //对话框宽度
        height: '95%',                          //对话框高度
    };

    //定义表格操作基本参数
    let actions = {
        //#authPermissions('system:config:add')
        addFlag: true,                                      //新增记录权限标志
        addUrl: module.path + 'add',                        //新增记录 URL
        //#end
        //#authPermissions('system:config:edit')
        editFlag: true,                                     //修改记录权限标志
        editUrl: module.path + 'edit',                      //修改记录 URL
        //#end
        //#authPermissions('system:config:del')
        removeFlag: true,                                   //删除记录权限标志
        removeUrl: module.path + 'delete',                  //删除记录 URL
        batchRemoveFlag: true,                              //批量删除标志
        batchRemoveUrl: module.path + 'delete',             //批量删除 URL
        //#end
        //#authPermissions('system:config:query')
        detailFlag: true,                                   //记录详情权限标志
        detailUrl: module.path + 'detail',                  //记录详情 URL
        //#end
        //事件处理
        handleEvent: (options, event, obj) => {
            if (event === 'add') {
                options.editDialog.height = '720px';
            }
            if (event === 'edit') {
                options.editDialog.height = '560px';
            }
        },
        //回调处理
        callbackEvent: (options, event, result) => {
        },
    };

    let rowButtons = '';
    //#authPermissions('system:user:resetPassword', 'system:user:assignRole')
    rowButtons = '<button class="pear-btn pear-btn-xs" round plain id="more_{{d.id}}" data-id="{{d.id}}"><i class="layui-icon layui-icon-triangle-d"></i>&nbsp;更多</button>';
    //#end

    //定义数据表格的 options，参考：https://layui.dev/docs/2/table/#options
    let options = {
        id: 'main-table',                                           //设定实例唯一索引
        elem: '#main-table',                                        //绑定原始 table 元素
        title: module.name,                                         //定义 table 的大标题（在文件导出等地方会用到）
        url: module.path + 'query',                                 //发送异步请求的 URL
        initSort: {'field': 'createdDatetime', 'type': 'desc'},     //初始排序状态
        toolbar: $.table.buildTableToolbar(actions),                //开启表格头部工具栏
        pagebar: '#main-pagebar',                                   //开启分页区域的自定义模板
        cols: [[                                                    //表头属性集
            {type: 'checkbox', align: 'center', width: 60},
            {field: 'status', align: 'center', width: 80, sort: true, title: '状态', templet: '#bean-status'},
            {field: 'account', align: 'left', minWidth: 100, width: '10%', sort: true, title: '登录账号'},
            {field: 'nickname', align: 'left', minWidth: 100, width: '15%', sort: true, title: '用户昵称'},
            {field: 'phone', align: 'left', width: 120, sort: true, title: '手机号'},
            {field: 'createdDatetime', align: 'center', width: 180, sort: true, title: '创建时间', templet: '#bean-createdDatetime'},
            {align: 'left', minWidth: 240, templet: $.table.buildRowToolbar(actions, rowButtons)},
        ]],
        done: (res, curr, count, origin) => {
            for (var i = 0; i < res.data.length; i++) {
                var data = [];
                var id = res.data[i].id;
                //#authPermissions('system:user:resetPassword')
                data.push({title: "重置密码", menuId: 100, id: id, disabled: id == 1});
                //#end
                //#authPermissions('system:user:assignRole')
                data.push({title: "分配角色", menuId: 101, id: id, disabled: id == 1});
                //#end

                dropdown.render({
                    elem: '#more_' + id,
                    data: data,
                    id: '#more_' + id,
                    click: (obj) => {
                        if (obj.menuId == 100) {
                            // 重置密码
                            resetPassword(obj.id);
                        }
                        if (obj.menuId == 101) {
                            // 分配角色
                            assignRole(obj.id);
                        }
                    }
                });
            }
        },
        module: module,             //表格模块基本参数
        queryForm: queryForm,       //查询表单基本参数
        editDialog: editDialog,     //编辑对话框基本参数
        actions: actions,           //表格操作基本参数
    };

    /*
     * 重置密码
     */
    let resetPassword = (id) => {
        let url = module.path + "resetPassword?id=" + id;
        let commitUrl = module.path + "resetPassword";
        $.modal.popupEditor(
            '重置密码',
            url,
            '480px',
            '320px',
            {
                buttonId: editDialog.submitButtonId,
                url: commitUrl,
                method: 'put',
                callback: (index, layero, that, result) => {
                    if (result.code === RESULT_CODE.SUCCESS) {
                        layer.close(index);
                    }
                }
            },
        );
    }

    /*
     * 分配角色
     */
    let assignRole = (id) => {
        let url = module.path + "assignRole?id=" + id;
        let commitUrl = module.path + "assignRole";
        $.modal.popupEditor(
            '分配角色',
            url,
            '720px',
            '95%',
            {
                buttonId: editDialog.submitButtonId,
                url: commitUrl,
                method: 'put',
                callback: (index, layero, that, result) => {
                    if (result.code === RESULT_CODE.SUCCESS) {
                        layer.close(index);
                    }
                },
            },
        );
    }

    let initDeptTree = () => {
        tree.render({
            elem: "#deptTree",
            onlyIconControl: true,
            showCheckbox: false,
            id: "deptTreeId",
            data: getDeptTreeData(),
            click: clickDeptTree,
            customName: {
                title: 'name',
            },
        });
    }

    let getDeptTreeData = () => {
        var data = [];
        $.ajax({
            url: "#CTX()/admin/system/dept/tree",    //后台数据请求地址
            async: false,
            success: function(result){
                data = result;
            },
        });

        // 展开所有
        spreadTreeData(data);

        return data;
    };

    let spreadTreeData = (data) => {
        if (data == undefined || data == null) return;
        data.forEach((item) => {item.spread = true; spreadTreeData(item.children)});
    };

    let clickDeptTree = (obj) => {
        $("[name='deptId']").val(obj.data.id);
        $.table.search(options.id);
    }

    $(document).ready(() => {
        initDeptTree();

        /**
         * 初始化数据表格
         */
        options = $.table.init(options);

        // 移动终端下隐藏部门树
        if ($.base.isMobile()){
            $(".dept-tree-div").hide();
        }
    });
});
</script>

</body>
</html>
